package com.tuozixuan.base;

import java.util.Objects;

import org.apache.commons.lang3.StringUtils;

public class Version {
	
	private String major;
	
	private String minor;
	
	private String revision;
	
	private String type;
	
	private Version(String major, String minor, 
			String revision, String type) {
		this.major = major;
		this.minor = minor;
		this.revision = revision;
		this.type = type;
	}

	public static Version of(final String version) {
		Objects.requireNonNull(version);
		
		String[] versionItems = version.split("-");
		if (versionItems.length != 2) {
			throw new IllegalArgumentException("version格式不正确。version：" + version);
		}
		String type = versionItems[1];
		String[] subItems = StringUtils.split(versionItems[0], '.');
		if (subItems.length != 3) {
			throw new IllegalArgumentException("version格式不正确。version：" + version);
		}
		return new Version(subItems[0], subItems[1], subItems[2], type);
	}
	
	public Version minorIncrement() {
		
		int newMinor = Integer.parseInt(minor) + 1;
		return new Version(major, String.valueOf(newMinor), revision, type);
	}
	
	public Version revisionIncrement() {
		
		int newRevision = Integer.parseInt(revision) + 1;
		return new Version(major, minor, String.valueOf(newRevision), type);
	}
	
	public Version revisionReset() {
		return new Version(major, minor, String.valueOf(0), type);
	}
	
	public Version type(String type) {
		return new Version(major, minor, revision, type);
	}
	
	public String getMajor() {
		return major;
	}

	public String getMinor() {
		return minor;
	}

	public String getRevision() {
		return revision;
	}

	public String getType() {
		return type;
	}
	
	@Override
	public String toString() {
		if (StringUtils.isNotBlank(type)) {
			return String.format("%s.%s.%s-%s", major, minor, revision, type);
		} else {
			return String.format("%s.%s.%s", major, minor, revision);
		}
	}
}
